<script setup lang="ts">
import { type Ref, reactive, ref, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import { mabangOrderDetail } from "@/api/mabang";
import { message } from "@/utils/message";
import { CopyDocument } from '@element-plus/icons-vue';

const { t } = useI18n();

// 声明 props 类型
export interface FormProps {
  formInline: {
    auto_id?: number;
    id?: string;
  };
}

const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({})
});

// 定义订单详情数据类型
interface OrderDetail {
  basic_info?: {
    auto_id: number;
    id: string;
    platform_order_id: string;
    sales_record_number: string;
    order_status: number;
    order_status_text: string;
    order_fee: number | string;
    currency_id: string;
    shipping_fee: number | string;
    declare_fee: number | string;
  };
  platform_info?: {
    platform_id: number;
    platform_id_text: string;
    shop_id: number;
    shop_id_text: string;
    shop_owner: string;
  };
  buyer_info?: {
    buyer_name: string;
    email: string;
    buyer_user_id: string;
    country_code: string;
    country_code_cn: string;
    country_code_en: string;
    province: string;
    city: string;
    post_code: string;
    street1: string;
    street2: string;
  };
  time_info?: {
    create_date: any;
    create_date_text: string;
    paid_time: any;
    paid_time_text: string;
    express_time: any;
    express_time_text: string;
    created_at: any;
    updated_at: any;
  };
  shipping_info?: {
    track_number: string;
    shipping_service: string;
    shipping_warehouse: string;
    order_weight: number | string;
    shipping_cost: number | string;
  };
  status_flags?: {
    is_virtual: number;
    is_virtual_text: string;
    is_refund: number;
    is_black_user: number;
    can_send: number;
  };
  remarks?: {
    order_remark_text: string;
    delivery_remark: string;
    buyer_message_text: string;
    seller_message: string;
  };
  goods_info?: {
    order_ellipsis_title: string;
  };
}

const orderDetail = ref<OrderDetail>({});
const loading = ref(false);

// 获取订单详情
const getOrderDetail = async () => {
  if (!props.formInline.auto_id && !props.formInline.id) {
    message("订单ID不存在", { type: "error" });
    return;
  }

  loading.value = true;
  try {
    const response = await mabangOrderDetail(props.formInline.auto_id || props.formInline.id);
    orderDetail.value = response.data as OrderDetail;
  } catch (error) {
    console.error('获取订单详情失败:', error);
    message('获取订单详情失败', { type: 'error' });
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getOrderDetail();
});

// 格式化时间
const formatDateTime = (timestamp: any): string => {
  if (!timestamp || timestamp === 0 || timestamp === '0' || timestamp === '') {
    return '-';
  }

  try {
    let date: Date;
    if (typeof timestamp === 'string') {
      if (/^\d+$/.test(timestamp)) {
        const time = parseInt(timestamp);
        if (isNaN(time) || time <= 0) return '-';
        date = new Date(time * 1000);
      } else {
        date = new Date(timestamp);
      }
    } else if (typeof timestamp === 'number') {
      if (timestamp <= 0) return '-';
      date = new Date(timestamp * 1000);
    } else {
      return '-';
    }

    if (isNaN(date.getTime())) return '-';

    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  } catch (error) {
    return '-';
  }
};

// 获取订单状态样式
const getStatusType = (status: number) => {
  const statusMap = {
    0: 'warning',
    1: 'warning',
    2: 'info',
    3: 'primary',
    4: 'success',
    5: 'danger',
    6: 'primary',
    7: 'danger',
    8: 'danger',
    9: 'warning',
    10: 'info',
    11: 'info'
  };
  return statusMap[status] || 'info';
};

// 解析商品内容格式
const parseGoodsInfo = (goodsTitle: string) => {
  if (!goodsTitle) return null;

  // 解析格式：(商品种类:2;商品个数:2)商品编号*数量:A647X126334-0010*1, box-newlls*1
  const headerMatch = goodsTitle.match(/\(商品种类:(\d+);商品个数:(\d+)\)/);
  const goodsMatch = goodsTitle.match(/商品编号\*数量:(.+)$/);

  if (!headerMatch || !goodsMatch) {
    return { raw: goodsTitle };
  }

  const goodsCount = parseInt(headerMatch[1]);
  const totalQuantity = parseInt(headerMatch[2]);
  const goodsListStr = goodsMatch[1];

  // 解析商品列表
  const goodsList = goodsListStr.split(', ').map(item => {
    const parts = item.split('*');
    if (parts.length === 2) {
      return {
        sku: parts[0],
        quantity: parts[1]
      };
    }
    return { sku: item, quantity: '1' };
  });

  return {
    goodsCount,
    totalQuantity,
    goodsList
  };
};
</script>

<template>
  <div v-loading="loading">
    <!-- 基础订单信息 -->
    <el-card class="detail-card" shadow="never">
      <template #header>
        <span class="card-title">基础订单信息</span>
      </template>

      <el-descriptions :column="3" border size="small">
        <el-descriptions-item label="订单ID" min-width="120px">
          <el-text type="primary">{{ orderDetail.basic_info?.id || '-' }}</el-text>
        </el-descriptions-item>
        
        <el-descriptions-item label="订单交易号">
          {{ orderDetail.basic_info?.sales_record_number || '-' }}
          <el-icon v-if="orderDetail.basic_info?.sales_record_number"
                   v-copy:click="orderDetail.basic_info?.sales_record_number"
                   class="copy-icon">
            <CopyDocument />
          </el-icon>
        </el-descriptions-item>
        <el-descriptions-item label="订单编号" min-width="150px">
          <span>{{ orderDetail.basic_info?.platform_order_id || '-' }}</span>
          <el-icon v-if="orderDetail.basic_info?.platform_order_id"
                   v-copy:click="orderDetail.basic_info?.platform_order_id"
                   class="copy-icon">
            <CopyDocument />
          </el-icon>
        </el-descriptions-item>

        <el-descriptions-item label="订单状态">
          <el-tag :type="getStatusType(orderDetail.basic_info?.order_status)" size="small">
            {{ orderDetail.basic_info?.order_status_text || '-' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="订单金额">
          <el-text type="primary" size="large">
            {{ orderDetail.basic_info?.order_fee_usd ? orderDetail.basic_info?.order_fee_usd + ' USD' : '-' }} 
          </el-text>
        </el-descriptions-item>
        <el-descriptions-item label="订单原始金额">
          <el-text type="primary" size="large">
            {{ orderDetail.basic_info?.order_fee || 0 }} {{ orderDetail.basic_info?.currency_id }}
          </el-text>
        </el-descriptions-item>
        <el-descriptions-item label="运费">
          {{ orderDetail.basic_info?.shipping_fee || 0 }} {{ orderDetail.basic_info?.currency_id }}
        </el-descriptions-item>

        <el-descriptions-item label="报关费用">
          {{ orderDetail.basic_info?.declare_fee || 0 }} {{ orderDetail.basic_info?.currency_id }}
        </el-descriptions-item>

        <el-descriptions-item label="发货状态">
          <el-tag :type="orderDetail.status_flags?.can_send === 1 ? 'success' : 'warning'" size="small">
            {{ orderDetail.status_flags?.can_send === 1 ? '可发货' : '不可发货' }}
          </el-tag>
        </el-descriptions-item>

        <el-descriptions-item label="客户来源">
          {{ orderDetail.basic_info?.customer_source || '-' }} 
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 商品信息 -->
    <el-card class="detail-card" shadow="never">
      <template #header>
        <span class="card-title">商品信息</span>
      </template>

      <template v-if="orderDetail.goods_info?.order_ellipsis_title">
        <template v-if="parseGoodsInfo(orderDetail.goods_info.order_ellipsis_title)?.goodsList">
          <el-descriptions :column="2" border size="small" style="margin-bottom: 16px;">
            <el-descriptions-item label="商品种类">
              <el-tag size="small" type="info">
                {{ parseGoodsInfo(orderDetail.goods_info.order_ellipsis_title).goodsCount }} 种
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="商品总数">
              <el-tag size="small" type="primary">
                {{ parseGoodsInfo(orderDetail.goods_info.order_ellipsis_title).totalQuantity }} 件
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>

          <div class="goods-list">
            <div class="goods-list-header">商品清单：</div>
            <div class="goods-items">
                             <div
                 v-for="(item, index) in parseGoodsInfo(orderDetail.goods_info.order_ellipsis_title).goodsList"
                 :key="index"
                 class="goods-item"
               >
                 <div class="goods-sku-wrapper">
                   <span class="goods-sku">{{ item.sku }}</span>
                   <el-icon
                     v-copy:click="item.sku"
                     class="copy-icon copy-icon-small"
                     title="复制商品编号"
                   >
                     <CopyDocument />
                   </el-icon>
                 </div>
                 <span class="goods-quantity">× {{ item.quantity }}</span>
               </div>
            </div>
          </div>
        </template>

        <template v-else>
          <el-descriptions :column="1" border size="small">
            <el-descriptions-item label="商品内容">
              {{ orderDetail.goods_info.order_ellipsis_title }}
            </el-descriptions-item>
          </el-descriptions>
        </template>
      </template>

      <template v-else>
        <el-descriptions :column="1" border size="small">
          <el-descriptions-item label="商品内容">-</el-descriptions-item>
        </el-descriptions>
      </template>
    </el-card>

    <!-- 平台和店铺信息 -->
    <el-card class="detail-card" shadow="never">
      <template #header>
        <span class="card-title">平台和店铺信息</span>
      </template>

      <el-descriptions :column="3" border size="small">
        <el-descriptions-item label="平台ID">
          {{ orderDetail.platform_info?.platform_id || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="平台名称">
          <el-tag size="small">{{ orderDetail.platform_info?.platform_id_text || '-' }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="店铺ID">
          {{ orderDetail.platform_info?.shop_id || '-' }}
        </el-descriptions-item>

        <el-descriptions-item label="店铺名称" :span="2">
          {{ orderDetail.platform_info?.shop_id_text || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="店铺负责人">
          {{ orderDetail.platform_info?.shop_owner || '-' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 买家信息 -->
    <el-card class="detail-card" shadow="never">
      <template #header>
        <span class="card-title">买家信息</span>
      </template>

      <el-descriptions :column="3" border size="small">
        <el-descriptions-item label="买家姓名">
          {{ orderDetail.buyer_info?.buyer_name || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="买家邮箱" :span="2">
          <span>{{ orderDetail.buyer_info?.email || '-' }}</span>
          <el-icon v-if="orderDetail.buyer_info?.email"
                   v-copy:click="orderDetail.buyer_info?.email"
                   class="copy-icon">
            <CopyDocument />
          </el-icon>
        </el-descriptions-item>

        <el-descriptions-item label="买家ID">
          {{ orderDetail.buyer_info?.buyer_user_id || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="国家">
          {{ orderDetail.buyer_info?.country_code_cn || orderDetail.buyer_info?.country_code_en || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="省份">
          {{ orderDetail.buyer_info?.province || '-' }}
        </el-descriptions-item>

        <el-descriptions-item label="城市">
          {{ orderDetail.buyer_info?.city || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="邮编">
          {{ orderDetail.buyer_info?.post_code || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="地址1">
          {{ orderDetail.buyer_info?.street1 || '-' }}
        </el-descriptions-item>

        <el-descriptions-item label="地址2" :span="3">
          {{ orderDetail.buyer_info?.street2 || '-' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 时间信息 -->
    <el-card class="detail-card" shadow="never">
      <template #header>
        <span class="card-title">时间信息</span>
      </template>

      <el-descriptions :column="2" border size="small">
        <el-descriptions-item label="下单时间">
          {{ orderDetail.time_info?.create_date_text || formatDateTime(orderDetail.time_info?.create_date) }}
        </el-descriptions-item>
        <el-descriptions-item label="支付时间">
          {{ orderDetail.time_info?.paid_time_text || formatDateTime(orderDetail.time_info?.paid_time) }}
        </el-descriptions-item>

        <el-descriptions-item label="发货时间">
          {{ orderDetail.time_info?.express_time_text || formatDateTime(orderDetail.time_info?.express_time) }}
        </el-descriptions-item>
        <el-descriptions-item label="录入系统时间">
          {{ formatDateTime(orderDetail.time_info?.created_at) }}
        </el-descriptions-item>

        <el-descriptions-item label="最后更新时间" :span="2">
          {{ formatDateTime(orderDetail.time_info?.updated_at) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 物流信息 -->
    <el-card class="detail-card" shadow="never">
      <template #header>
        <span class="card-title">物流信息</span>
      </template>

      <el-descriptions :column="3" border size="small">
        <el-descriptions-item label="快递单号">
          <span>{{ orderDetail.shipping_info?.track_number || '-' }}</span>
          <el-icon v-if="orderDetail.shipping_info?.track_number"
                   v-copy:click="orderDetail.shipping_info?.track_number"
                   class="copy-icon">
            <CopyDocument />
          </el-icon>
        </el-descriptions-item>
        <el-descriptions-item label="物流服务">
          {{ orderDetail.shipping_info?.shipping_service || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="发货仓库">
          {{ orderDetail.shipping_info?.shipping_warehouse || '-' }}
        </el-descriptions-item>

        <el-descriptions-item label="订单重量">
          {{ orderDetail.shipping_info?.order_weight || 0 }}g
        </el-descriptions-item>
        <el-descriptions-item label="物流成本" :span="2">
          {{ orderDetail.shipping_info?.shipping_cost || 0 }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 备注信息 -->
    <el-card class="detail-card" shadow="never" v-if="orderDetail.remarks">
      <template #header>
        <span class="card-title">备注信息</span>
      </template>

      <el-descriptions :column="1" border size="small">
        <el-descriptions-item label="订单备注" v-if="orderDetail.remarks?.order_remark_text">
          {{ orderDetail.remarks.order_remark_text }}
        </el-descriptions-item>
        <el-descriptions-item label="发货备注" v-if="orderDetail.remarks?.delivery_remark">
          {{ orderDetail.remarks.delivery_remark }}
        </el-descriptions-item>
        <el-descriptions-item label="买家留言" v-if="orderDetail.remarks?.buyer_message_text">
          {{ orderDetail.remarks.buyer_message_text }}
        </el-descriptions-item>
        <el-descriptions-item label="卖家留言" v-if="orderDetail.remarks?.seller_message">
          {{ orderDetail.remarks.seller_message }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.detail-card {
  margin-bottom: 16px;

  &:last-child {
    margin-bottom: 0;
  }
}

.card-title {
  font-weight: 600;
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.copy-icon {
  margin-left: 8px;
  cursor: pointer;
  color: var(--el-color-primary);

  &:hover {
    color: var(--el-color-primary-light-3);
  }
}

:deep(.el-descriptions__label) {
  font-weight: 500;
  width: 120px;
}

:deep(.el-descriptions__content) {
  word-break: break-all;
}

:deep(.el-card__header) {
  padding: 12px 16px;
  border-bottom: 1px solid var(--el-border-color-light);
}

:deep(.el-card__body) {
  padding: 16px;
}

.goods-list {
  margin-top: 8px;
}

.goods-list-header {
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
  font-size: 14px;
}

.goods-items {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.goods-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background-color: var(--el-fill-color-lighter);
  border-radius: 4px;
  border-left: 3px solid var(--el-color-primary);
}

.goods-sku-wrapper {
  display: flex;
  align-items: center;
  gap: 6px;
}

.goods-sku {
  font-family: 'Consolas', 'Monaco', monospace;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.copy-icon-small {
  font-size: 14px;
  cursor: pointer;
  color: var(--el-color-info);
  opacity: 0.7;
  transition: all 0.2s;
}

.copy-icon-small:hover {
  color: var(--el-color-primary);
  opacity: 1;
  transform: scale(1.1);
}

.goods-quantity {
  font-weight: 600;
  color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}
</style>
